<?php

namespace app\admin\controller\vactivities;

use app\admin\model\Conference;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 标签管理
 *
 * @icon fa fa-ticket
 */
class Ticket extends Backend
{
    
    /**
     * Ticket模型对象
     * @var \app\admin\model\vactivities\Ticket
     */
    protected $ticketModel = null;
    protected $activityModel = null;
    protected $model = null;

    protected $searchFields = 'id,name';


    public function _initialize()
    {
        parent::_initialize();
        $this->ticketModel = new \app\admin\model\vactivities\Ticket;
        $this->activityModel = new \app\admin\model\vactivities\Activity;

        $this->model = new \app\admin\model\vactivities\Ticket;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 门票管理
     */

    public function index(){
        $tag = $this->request->param('tag');
        $mywhere['admin_id'] = $this->auth->id;
        $mywhere['isend'] = ($tag==2)?1:0;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->activityModel
                ->where($where)
                //->where($map)
                ->where($mywhere)
                ->order($sort, $order)
                ->count();
            $list = $this->activityModel
                ->where($where)
                //->where($map)
                ->where($mywhere)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            if(!empty($list)) {
                foreach ($list as $item=>$value) {
                    switch ($value['isticket']){
                        case 0:
                            $value['isticket'] = "注册加入活动";
                            break;
                        case 1:
                            $value['isticket'] = "入场劵加入活动";
                            break;
                        case 2:
                            $value['isticket'] = "直接加入活动";
                            break;
                    }
                    //$value['isend'] =($value['isend']==0)?'开启':'已关闭';
                    $value['endTime']  = date('Y-m-d H:i:s',$value['endTime']);
                    $tempData = null;
                    $tempData = $this->ticketModel->where('activity_id='.$value['id'])->select();
                    $tempNumber = $tempT = 0;
                    if(!empty($tempData)){
                        foreach ($tempData as $miitem =>$mivalue){
                            $tempNumber += $mivalue['number'];
                            $tempT += $mivalue['temp'];
                        }
                    }
                    $list[$item]['totalNumber'] = $tempNumber;
                    $list[$item]['totalTemp']  = $tempT;
                }
            }

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->view->assign("tag", empty($tag)?1:$tag);
        return $this->view->fetch();
    }
    /**
     * 添加门票
     */
    public function ticketadd()
    {
        $activity_id = $this->request->param("activity_id");
        $activityList =  $this->activityModel->where('admin_id='.$this->auth->id)->column('name','id','isticket');
        $row = $this->activityModel->get($activity_id);
        if(!$row){
            $this->error(__('No Results were found'));

        }
        $row = $row->toArray();
        //$activityList =  $this->activityModel->where('admin_id=555555')->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['temp'] = $params['number'];
                $params['price'] = $params['price']*100;
                $params['admin_id'] = $this->auth->id;
                $params['type'] = 2;
                $params['createTime'] = date('Y-m-d H:i:s',time());
                $params['updateTime'] = date('Y-m-d H:i:s',time());
                $params['start_time'] =  strtotime($params['start_time']);
                $params['end_time'] =  strtotime($params['end_time']);
                $params['ticket_type'] =  $row['isticket'];
                $params['status'] = 1;
                $this->ticketModel->insert($params);
            }
            return $this->success('添加成功');
        }
        //dump($activityList);
        $this->view->assign("activity_id",$activity_id);
        $this->view->assign("activityList",$activityList);
        return $this->view->fetch();
    }
    /**
     * 编辑门票
     */
    public function ticketlist()
    {
        $activity_id = $this->request->param("activity_id");
        $mywhere = [];
        if(!$activity_id){
            $this->error(__('Params err'));
        }else{
            $mywhere["activity_id"] = $activity_id;
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->ticketModel
                //->with(['account'])
                ->where($mywhere)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $nLIst = $list->items();
            foreach ($nLIst as $row=>$value) {
                $nLIst[$row]['price'] = number_format($value['price']/100,2);
            }
            $result = array("total" => $list->total(), "rows" => $nLIst,'activity_id'=>$activity_id);
            return json($result);
        }
        $this->view->assign("activity_id", $activity_id);
        return $this->view->fetch();
    }
    /**
     * 查看已关闭门票
     */
    public function ticketview()
    {
        $activity_id = $this->request->param("activity_id");
        $mywhere = [];
        if(!$activity_id){
            $this->error(__('Params err'));
        }else{
            $mywhere["activity_id"] = $activity_id;
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->ticketModel
                //->with(['account'])
                ->where($mywhere)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items(),'activity_id'=>$activity_id);
            return json($result);
        }
        $this->view->assign("activity_id", $activity_id);
        return $this->view->fetch();
    }



    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $actInfo = $this->activityModel->get($row->activity_id);
        if(!$actInfo){
            $this->error(__('No Results were found'));

        }
        $act = $actInfo->toArray();//获取活动信息

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['start_time'] =strtotime($params['start_time']);
                $params['end_time'] =strtotime($params['end_time']);
                $params['price'] =(int)($params['price'])*100;
                $params['ticket_type'] =  $act['isticket'];
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }




}
